package com.zj.base.permission.checker;

import android.app.Activity;
import android.content.DialogInterface;

import com.zj.base.permission.ConfigurationModules;
import com.zj.base.permission.interfaces.OnActionClickListener;
import com.zj.base.permission.interfaces.OnPermissionCheckListener;
import com.zj.base.permission.manifests.Op_PermissionCheekUtils;
import com.zj.base.permission.utils.JumpToSettingUtils;
import com.zj.base.utils.SPUtils;
import com.zj.base.utils.ToastUtils;

/**
 * Created by zhaojie on 2018/5/29.
 */

public class KITKAT_checker extends BasePermissionChecker {

    public KITKAT_checker(Activity activity) {
        super(activity);
    }

    @Override
    public void check() {
        //取出暂未被授权的
        for (ConfigurationModules module : getPermissions()) {
            if (listener != null)
                listener.startCheck(module);
            boolean isIgnore = isIgnore(module);
            boolean hasPermission = Op_PermissionCheekUtils.invokeDeclaredMethod(activity, module.declaredMethodName, module.opName);
            if (!hasPermission && !isIgnore) {
                //将状态保存在map内，只通过系统授权询问一次，为false时表示用户已经拒绝；
                addFail(module);
            } else {
                addSuccess(module);
                if (listener != null)
                    listener.result(module, OnPermissionCheckListener.State.SUCCESS);
            }
        }
        if (isEnd()) {
            //请求的权限都已经授权
            if (listener != null)
                listener.onSuccess(getPermissions());
            SPUtils.put(activity, "isFirstIn", false);
        } else {
            //有没有完成授权的权限，需要进行申请授权；
            final ConfigurationModules module = getFailPermission(0);
            showAlert(true, module, new OnActionClickListener() {
                @Override
                public void cancel(DialogInterface dialog) {
                    if (module.isForce) {
                        ToastUtils.show("必要权限获取失败，请重新授权");
                        activity.finish();
                        return;
                    } else {
                        addIgnore(module);
                    }
                    if (listener != null)
                        listener.result(module, module.isForce ? OnPermissionCheckListener.State.FAIL : OnPermissionCheckListener.State.FAIL_NOT_FORCE);
                    if (!isEnd()) check();
                    else {
                        if (listener != null) listener.onSuccess(getPermissions());
                    }
                }

                @Override
                public void fulfil(DialogInterface dialog) {
                    JumpToSettingUtils.CheekAndJump(activity, PERMISSIONCODE);
                }
            });
        }
    }
}
